<!--
  11选5彩球选择器
-->
<template>
  <div class="bg-white bb-l">
    <div class="tips p-3" v-html="config.tips"></div>
    <template v-if="rule.bold">
      <ball-group group="胆码" :rule="rule.name" :missing="missings[0]" :conflicts="conflicts(groups, 0)" v-model="groups[0]" :max="max"/>
      <ball-group group="拖码" :rule="rule.name" :missing="missings[0]" :conflicts="conflicts(groups, 1)" v-model="groups[1]"/>
    </template>
    <template v-else>
      <ball-group :group="group" v-bind="config" :missing="missing(i)" :conflicts="conflicts(groups, i)"
                  v-model="groups[i]" v-for="(group, i) in config.groups" :key="i"/>
    </template>
  </div>
</template>

<script>
import { gain, gen, rules } from './calculator'
import BallGroup from './ball-group'

export default {
  components: {BallGroup},
  props: {
    value: Object,
    rule: Object,
    missings: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  name: 'ball-select',
  data: () => ({
    groups: [] // 已选号码分组
  }),
  created () {
    this.$on('clear', this.clear)
    this.$on('gen', () => {
      this.groups = gen(this.rule.rule)
    })
  },
  methods: {
    conflicts (groups, exclude) {
      var {rule, bold} = this.rule
      if (!bold && rule.charAt(0) != 'l') {
        return
      }

      return groups.filter(function (g, i) {
        return exclude !== i
      })
    },
    missing (index) {
      if (!this.missings) return []
      switch (this.rule.rule) {
        case 'q1':
        case 'q2d':
        case 'q3d':
          return this.missings[index + 1]
        default:
          return this.missings[0]
      }
    },
    clear () {
      this.groups = [[]]
    }
  },
  computed: {
    config () {
      var {rule, bold} = this.rule
      if (!rule) {
        return {}
      }
      var config = rules[rule]
      var tips = config.tips(bold)

      return Object.assign({}, config, {tips, rule: config.name})
    },
    max () {
      var {rule, bold} = this.rule
      return bold && parseInt(rule.substr(1, 1)) - 1
    }
  },
  watch: {
    groups (g) {
      var {rule, bold} = this.rule
      this.$emit('input', gain(g, rule, bold))
    },
    rule () {
      this.clear()
    }
  }
}
</script>
